<?php
    namespace app\api\model;
    use app\common\model\AdminNotify;
    use app\common\model\Model;
    use think\Db;
    
//  model 类
    class OrderModel extends Model
    {
        const TABLE_NAME = 'order';
        const CACHE_EXPIRE_LEVEL = self::CACHE_EXPIRE_LEVEL_4;

        protected $name = self::TABLE_NAME;
        
        const STATUS_UN_PAY =1; //没有支付
        const STATUS_PAY=2; //已支付，但没有 发货
        const STATUS_DELIVERY=3;//已发货
        const STATUS_COMPLETE =4; //已完成
        const STATUS_CANCEL =5; // 已取消
       

        // 购买商品， 生成 订单
        /**
         * @param $user_id
         * @param $order_info
         * @param int $address_id 0 表示 用户填写的默认地址,在 此之前需判断 用户是否有默认地址
         * @param int $payType
         * @return bool|int|string
         */
        public static function generateGoodsOrders($user_id, $order_info, $address_id=0, $payType = 6){

            if(empty($order_info) || !$user_id ){
                return false;
            }
            $now =time();
            //优惠券
            $is_coupon =0;
            $coupon_sum=0;
            //积分 数 和 添加 积分 数据
            $total_points_num = 0;


            Db::startTrans();
            //检查 商品信息 是否 完整, 库存量是否足够
            $goods_order_res = self::getGoodsOrderInfo($order_info,$user_id,$now);
            if(!$goods_order_res['status'])
            {
                Db::rollback();
                return $goods_order_res;
            }
            try{
                //订单 公共信息 表
                $order_id = self::insert([
                    'address_id'=>$address_id,
                    //商品 分类 的类别数，不是 总的个数
                    'goods_num'=>$goods_order_res['goods_num'],
                    'is_coupon'=>$is_coupon,
                    'coupon_sum'=>$coupon_sum,
                    'nominal_amount'=>$goods_order_res['nominal_amount'] ,
                    'actual_amount'=>$goods_order_res['nominal_amount'] - $coupon_sum,
                    'pay_type'=>$payType,

                ],false,true);
                // 生成订单详情表

                $query = self::commonQuery('order_info');

                foreach ($goods_order_res['data'] as $k=>$v)
                {
                    //减去库存数
                    Goods::descGoodsNum($v['goods_id'],$v['num']);
                    $v['order_id']=$order_id;

                    $order_goods_id= $query->insert($v,false,true);
                    //添加 积分记录
                    $goods_points_num= Goods::getGoodsPoints($v['goods_id']);
                    if($goods_points_num >0)
                    {
                        $goods_points_num =$goods_points_num * $v['num'];
                        PointsRecord::addRecord($user_id,PointsRecord::POINTS_GOODS,$order_goods_id,$goods_points_num);
                        $total_points_num+=$goods_points_num;
                    }
                }
               //添加 用户 积分数
                User::incrUserPoints($user_id,$total_points_num);
            }catch(\Exception $e){
                Db::rollback();
                // return ($e->getMessage());
                 return ['status'=>false,'msg'=>$e->getMessage()];
            }
            Db::commit();
            return ['status'=>true,'order_id'=>$order_id];
        }
        
        // 获取当前订单状态
        public static function getOrderStatusById($id){
            if(!$id){
                return 0;
            }
            $status=self::commonQuery('order')->where('order_id',$id)->column('status');

            return $status[0]?$status[0]:0;
        }

        //  取消订单的 状态修改
        public static function changeOrderStatusById($id , $sta = 5){
            if(!$id ){
                return 0;
            }
            $status= Db('order')->where('order_id', $id)->column('status');

            if($status[0] == $sta){
                return 1;
            }

            $res=Db('order')->where('order_id',$id)->update(['status'=>$sta]);

            return $res?$res:false;
        }


        // 根据 user_id 获取 订单信息
        public static function getUserOrderList($user_id,$order_info_id,$up_time,$limit=self::LIMIT){

//            $where['user_id']=$user_id;
//
//            $where['is_del']=0;
            $query = self::commonQuery('order_info')
                ->where(['user_id'=>$user_id,'add_time'=>['elt',$up_time],'is_del'=>0]);
            if($order_info_id > 0)
            {
                $query->where(['order_info_id'=>['lt',$order_info_id]]);
            }
           
            return $query->order('add_time desc')->limit(self::LIMIT)->select();

        }
        
  //检查 商品 信息
        private  static function getGoodsOrderInfo($order_info,$user_id,$now)
        {
            $data_order_info = [];
            $i=0;
            $goods_num=0; //商品 分类 的类别数，不是 总的个数
            $nominal_amount=0;
            $order_sn=date('YmdHis',$now) . rand(100000, 999999);
            foreach ($order_info as $key=>$val){
                $goods_info = Goods::getGoodsInfoForUpdate($val['goods_id']);
                if(empty($goods_info))
                {
                    return ['status'=>false,'msg'=>'没有商品信息'];
                }
                if($goods_info['stock'] < $val['num'])
                {
                    return ['status'=>false,'msg'=>'商品剩余不足'];
                }
                $data_order_info[$i]=[
                    'goods_id'=>$val['goods_id'],
                    'user_id'=>$user_id,
                    'add_time'=>$now,
                    'price'=>$goods_info['price'],
                    'num'=>$val['num'],
                    'order_sn'=>$order_sn.$i
                ];
                $i++;
                $goods_num++;
                $nominal_amount += $goods_info['price'] * $val['num'];

            }

            return ['status'=>true,'data'=>$data_order_info,'goods_num'=>$goods_num,'nominal_amount'=>$nominal_amount];
        }

        //获取 商品ID
        public static function getGoodsId($id)
        {
            $info = self::commonQuery('order_info',self::CACHE_EXPIRE_LEVEL_4)
                   ->where(['order_info_id'=>$id])
                  ->find();
            return empty($info)?0:$info['goods_id'];
        }
        public static function handleOrderList($list,$user_id)
        {

            if(empty($list)){
                return [];
            }
            foreach ($list as $key=>$val)
            {
                $list[$key]=array_merge($val,Goods::handleGoodsInfo(Goods::getGoodsInfo($val['goods_id'],self::CACHE_EXPIRE_LEVEL),$user_id));

                $list[$key]['order_add_date']= date('Y-m-d H:i',$val['add_time']);

            }

            return $list;
        }

        //删除订单
        public static function deleteOrder($user_id,$order_id){
           return  self::commonQuery('order_info')
               ->where(['user_id'=>$user_id,'order_id'=>$order_id])
                ->setField('is_del',1);
        }
        public static function getNotifyParam($order_id)
        {
            return ['module'=>ORDER_MODULE,'module_id'=>$order_id,
                  'notify_type'=>AdminNotify::ORDER_GOODS,
            ];
        }
}

